package org.example.setup.service.impl;

import org.example.setup.domain.CustomerChat;
import org.example.setup.mapper.ChatMapper;
import org.example.setup.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ChatServiceImpl implements ChatService {

    @Autowired
    private ChatMapper chatMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    // 添加聊天记录
    @Override
    public int chatAdd(CustomerChat customerChat) {
        // 设置创建时间为当前时间
        customerChat.setCreateTime(new Date());

        ListOperations<String, CustomerChat> listOperations = redisTemplate.opsForList();
        List<CustomerChat> rows = listOperations.range("EXPRESS:CUSTOMER:CHAT", 0, -1);

        // 如果 Redis 中的列表为空
        if (rows == null || rows.isEmpty()) {
            customerChat.setId(1L);
            rows.add(customerChat);
            listOperations.leftPushAll("EXPRESS:CUSTOMER:CHAT", rows);
            return chatMapper.chatAdd(customerChat);
        } else {
            // 对列表进行排序，根据 ID 降序排列
            Collections.sort(rows, new Comparator<CustomerChat>() {
                @Override
                public int compare(CustomerChat o1, CustomerChat o2) {
                    return o2.getId().compareTo(o1.getId());
                }
            });
            customerChat.setId(rows.get(0).getId() + 1);
            listOperations.leftPush("EXPRESS:CUSTOMER:CHAT", customerChat);
        }
        return chatMapper.chatAdd(customerChat);
    }

    // 根据 IP 地址查询聊天记录
    @Override
    public List<CustomerChat> selectByIp(String registerIp) {
        ListOperations<String, CustomerChat> listOperations = redisTemplate.opsForList();
        List<CustomerChat> rows = listOperations.range("EXPRESS:CUSTOMER:CHAT", 0, -1);

        if (rows!= null &&!rows.isEmpty()) {
            // 过滤出 IP 地址匹配的聊天记录
            List<CustomerChat> filteredRows = rows.stream()
                    .filter(chat -> registerIp.equals(chat.getRegisterIp()))
                    .collect(Collectors.toList());
            return filteredRows;
        }

        List<CustomerChat> customerChatList = chatMapper.selectAll(registerIp);
        if (customerChatList!= null &&!customerChatList.isEmpty()) {
            listOperations.leftPushAll("EXPRESS:CUSTOMER:CHAT", customerChatList);
            return customerChatList;
        }

        return new ArrayList<>();
    }
}
